#include "myenv.h"
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern char **environ;

int mysetenv(const char *name, const char *value, int overwrite) {
    if (name == NULL || strlen(name) == 0 || strchr(name, '=') != NULL) {
        errno = EINVAL;
        return -1;
    }
    if (value == NULL) {
        errno = EINVAL;
        return -1;
    }

    char *old_value = getenv(name);
    if (old_value != NULL && overwrite == 0) {
        return 0;
    }

    size_t env_size = strlen(name) + strlen(value) + 2; // +2 for '=' and '\0'
    char *env_str = malloc(env_size);
    if (env_str == NULL) {
        errno = ENOMEM;
        return -1;
    }
    snprintf(env_str, env_size, "%s=%s", name, value);
    return putenv(env_str);
}

int myunsetenv(const char *name) {
    if (name == NULL || strlen(name) == 0 || strchr(name, '=') != NULL) {
        errno = EINVAL;
        return -1;
    }

    char *old_value = getenv(name);
    if (old_value == NULL) {
        return 0;
    }

    const size_t name_len = strlen(name);
    char **ep = environ;
    char **write_pos = environ;
    size_t count = 0;
    
    // 遍历environ数组，计算剩余元素数量
    while (*ep != NULL) {
        if (strncmp(*ep, name, name_len) == 0 && (*ep)[name_len] == '=') {
            free(*ep);
        } else {
            if (write_pos != ep) {
                *write_pos = *ep;
            }
            write_pos++;
            count++;
        }
        ep++;
    }
    
    // 重新分配environ内存
    if (count > 0) {
        char **new_environ = realloc(environ, (count + 1) * sizeof(char *));
        if (new_environ != NULL) {
            environ = new_environ;
            environ[count] = NULL;
        }
    } else {
        free(environ);
        environ = NULL;
    }
    return 0;
}